"""
HTML parser for extracting FPS data
"""
from bs4 import BeautifulSoup
from typing import Dict, List, Optional
import re

class FPSDataParser:
    RESOLUTION_MAPPING = {
        '1920 × 1080': 0,  # 1080p
        '2560 × 1440': 1,  # 1440p
        '3840 × 2160': 2   # 2160p
    }
    
    @staticmethod
    def extract_fps_data(html_content: str) -> List[Dict]:
        """
        Extract FPS data from HTML content
        Returns a list of dictionaries containing FPS data for each resolution
        """
        soup = BeautifulSoup(html_content, 'html.parser')
        fps_data = []
        
        # 1. 找到Top 5 Popular Resolutions标题
        header = soup.find(lambda tag: tag.name in ['h3', 'h4'] and 'Top 5 Popular Resolutions' in tag.text)
        if not header:
            print('未找到Top 5 Popular Resolutions标题')
            return []
        
        # 2. 找到紧跟其后的table
        fps_table = header.find_next('table')
        if not fps_table:
            print('未找到分辨率FPS数据表格')
            return []
        
        # 3. 遍历tbody的每一行
        tbody = fps_table.find('tbody')
        if not tbody:
            print('未找到表格主体')
            return []
            
        for row in tbody.find_all('tr'):
            cols = row.find_all('td')
            if len(cols) < 5:
                continue
            
            # 第一列分辨率
            res_text = cols[0].get_text(strip=True)
            # 兼容span嵌套和不同显示方式
            res_type = None
            for key in FPSDataParser.RESOLUTION_MAPPING:
                if key in res_text:
                    res_type = FPSDataParser.RESOLUTION_MAPPING[key]
                    break
            
            if res_type is None:
                continue
            
            # 后四列分别为四种画质的FPS
            fps_values = []
            for i in range(1, 5):
                fps_str = cols[i].get_text(strip=True)
                try:
                    val = float(fps_str.split()[0])
                    fps_values.append(val)
                except Exception:
                    fps_values.append(0.0)
            
            if len(fps_values) == 4:
                fps_data.append({
                    'resolution_type': res_type,
                    'low_setting_fps': fps_values[0],
                    'medium_setting_fps': fps_values[1],
                    'high_setting_fps': fps_values[2],
                    'ultra_setting_fps': fps_values[3]
                })
        
        return fps_data 